<template>
  <div class="app-container">

    <el-card>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="最近时间">
        <el-radio-group style=" margin-left: 20px;" size="mini" v-model="radio" @change="handlerq">
        <el-radio-button label="1">近1天</el-radio-button>
        <el-radio-button label="2">近1个月</el-radio-button>
        <el-radio-button label="3">近3个月</el-radio-button>
      </el-radio-group>
      </el-form-item>
    <el-form-item label="统计时间" prop="startDate">
      <el-date-picker v-model="valueTime" type="daterange" align="right" unlink-panels size="mini" range-separator="至"
                      :clearable="false" start-placeholder="开始日期" value-format="yyyy-MM-dd" end-placeholder="结束日期"
                      @change="handleQuery">
      </el-date-picker>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
    </el-form-item>
  </el-form>
    </el-card>
    <div class="metrics-container">
      <div class="metric-card" v-for="metric in metrics" :key="metric.id" :class="getMetricClass(metric.id)">
        <div class="metric-title">{{ metric.title }}</div>
        <div class="metric-value">{{ metric.value }}</div>
        <div class="metric-percentage">{{ metric.percentage }}%</div>
      </div>
    </div>

    <!-- Chart Section -->
    <el-card style="margin-bottom: 20px">
        <div>
          <div slot="header" style="float:left"><span><i class="el-icon-pie-chart"></i>发送走势图</span></div>
          <div style="float:right;">
            <el-radio-group style="margin-bottom: 30px;" size="mini">
            </el-radio-group>
          </div>
        </div>
        <div class="el-table el-table--enable-row-hover el-table--medium">
          <div ref="chartContainer" style="height: 420px"/>
        </div>
      </el-card>


    <div class="chart-section">
      <el-tabs v-model="tabName" style="width: 100%;height: 100%" >
        <el-tab-pane label="详细数据表" name="task"  :key ="'task'" style="font-size: 22px">
          <el-table v-loading="loading" :data="tableData">
        <el-table-column label="日期" align="center" prop="sendDate"  width="120">
        </el-table-column>
        <el-table-column label="请求" align="center" prop="requestNum" >

        </el-table-column>
        <el-table-column label="送达" align="center" prop="" >
          <template slot-scope="scope">
            <div style=" height: 30px; line-height: 30px;">
              <div style="float: none;font-size: 14px;color: #181d38">{{ scope.row.deliveredNum }}</div>
            </div>
            <div style=" height: 30px; line-height: 30px;">
              <div style="float:none;font-size: 14px;color: #181d38">{{ scope.row.deliveredPercent }}%</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="无效邮件" align="center" prop="">
          <template slot-scope="scope">
            <div style=" height: 30px; line-height: 30px;">
              <div style="float: none;font-size: 14px;color: #181d38">{{ scope.row.invalidEmailsNum }}</div>
            </div>
            <div style=" height: 30px; line-height: 30px;">
              <div style="float:none;font-size: 14px;color: #181d38">{{ scope.row.invalidEmailsPercent }}%</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="打开" align="center" prop="">
          <template slot-scope="scope">
            <div style=" height: 30px; line-height: 30px;">
              <div style="float: none;font-size: 14px;color: #181d38">{{ scope.row.openNum }}</div>
            </div>
            <div style=" height: 30px; line-height: 30px;">
              <div style="float:none;font-size: 14px;color: #181d38">{{ scope.row.openPercent }}%</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="点击" align="center" prop="" >
          <template slot-scope="scope">
            <div style=" height: 30px; line-height: 30px;">
              <div style="float: none;font-size: 14px;color: #181d38">{{ scope.row.clickNum }}</div>
            </div>
            <div style=" height: 30px; line-height: 30px;">
              <div style="float:none;font-size: 14px;color: #181d38">{{ scope.row.clickPercent }}%</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="垃圾举报" align="center" prop="" >
          <template slot-scope="scope">
            <div style=" height: 30px; line-height: 30px;">
              <div style="float: none;font-size: 14px;color: #181d38">{{ scope.row.spamReportedNum }}</div>
            </div>
            <div style=" height: 30px; line-height: 30px;">
              <div style="float:none;font-size: 14px;color: #181d38">{{ scope.row.spamReportedPercent }}%</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="取消订阅" align="center" prop="" >
          <template slot-scope="scope">
            <div style=" height: 30px; line-height: 30px;">
              <div style="float: none;font-size: 14px;color: #181d38">{{ scope.row.unsubscribeNum }}</div>
            </div>
            <div style=" height: 30px; line-height: 30px;">
              <div style="float:none;font-size: 14px;color: #181d38">{{ scope.row.unsubscribePercent }}%</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="计费邮件" align="center" prop="requestNum" >
        </el-table-column>
      </el-table>
        </el-tab-pane>
        <el-tab-pane label="无效原因" name="record" :key ="'record'" style="font-size: 22px">
          <el-table v-loading="loading" :data="invalidstatData">
            <el-table-column label="日期" align="center" prop="sendDate"  width="120">
            </el-table-column>
            <el-table-column label="收信域名" align="center" prop="domain" >
            </el-table-column>
            <el-table-column label="黑名单" align="center" prop="sendcloudBlacklist" >
            </el-table-column>
            <el-table-column label="取消订阅" align="center" prop="ubsubscribe">
            </el-table-column>
            <el-table-column label="服务器不可达" align="center" prop="espUnvaliable">
            </el-table-column>
            <el-table-column label="收件人格式错误" align="center" prop="recipientAddressError">
              <template slot-scope="scope">
                {{ scope.row.recipientAddressError || '0'}}
              </template>
            </el-table-column>
            <el-table-column label="ip或者域名被拒" align="center" prop="ipOrDomainRejected" >
              <template slot-scope="scope">
                {{ scope.row.ipOrDomainRejected || '0'}}
              </template>
            </el-table-column>
            <el-table-column label="收件人不存在" align="center" prop="recipientNotFound" >
            </el-table-column>
            <el-table-column label="垃圾邮件" align="center" prop="spamEmail" >
            </el-table-column>
            <el-table-column label="发信人或者收件人被拒" align="center" prop="senderOrRecipientRejected" >
            </el-table-column>
            <el-table-column label="其他" align="center" prop="others" >
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {
  getStatdaylist,
  getInvalidstatlist, getStatdayTotalList
} from '@/api/email/sendcloud'
import { GetDayA, GetMonA, GetMonB } from '@/api/public'
import { listEmailManage } from '@/api/email/EmailManage'
export default {
  name: 'DataSend',
  components: { },

  data() {
    return {
      showSearch: true,
      tabName: 'task',
      activeTab: 'sendData',
      activeControl: '发送追踪',
      tabs: [
        { id: 'sendData', name: '发信数据' },
        { id: 'overseas', name: '海外通' },
        { id: 'network', name: '网易通' },
        { id: 'new', name: '新浪通' }
      ],
      metrics: [

      ],
      valueTime:[],
      radio: 1, //1天，1月,3月
      senderList: [],
      chartControls: ['发送追踪', '发送独立追踪', '发送', '追踪'],
      chart: null,
      tableHeaders: [
        { key: 'date', label: '日期' },
        { key: 'requests', label: '请求' },
        { key: 'delivered', label: '送达' },
        { key: 'invalid', label: '无效邮件' },
        { key: 'softBounce', label: '软退信' },
        { key: 'opens', label: '打开' },
        { key: 'clicks', label: '点击' },
        { key: 'spamReports', label: '垃圾举报' },
        { key: 'unsubscribes', label: '取消订阅' },
        { key: 'billableEmails', label: '计费邮件' }
      ],
      loading: false,
      tableData: [],
      invalidstatData: [],
      // 查询参数
      queryParams: {
        apiUser: null,
        startDate: null,
        endDate: null,
        apiKey: null,
        pageNum: 1,
        pageSize: 20
      },
    }
  },
  created() {
    this.getSenderList();
    this.getList();
    this.getInvalidStatList();
  },
  mounted() {
    window.addEventListener('resize', this.resizeChart);
  },
  methods: {
    getMetricClass(metricId) {
      const colorMap = {
        'requests': 'metric-blue',
        'delivered': 'metric-green', 
        'processed': 'metric-purple',
        'invalid': 'metric-red',
        'opened': 'metric-orange',
        'complaint': 'metric-yellow',
        'unsubscribe': 'metric-gray'
      };
      return colorMap[metricId] || 'metric-default';
    },
    
    initChart() {
      this.$nextTick(() => {
        if (!this.$refs.chartContainer) {
          console.error('图表容器未找到');
          return;
        }

        console.log("getList" + this.tableData);

        // 如果已经有图表实例，先销毁
        if (this.chartContainer) {
          this.chartContainer.dispose();
        }

        this.chartContainer = echarts.init(this.$refs.chartContainer);
        var otherqqs = [];
        var otherrq = [];
        var othewx = [];
        var othedk = [];
        var option;
        this.tableData.forEach(item => {
            otherrq.push(item.sendDate);
            otherqqs.push(item.requestNum);
            othewx.push(item.invalidEmailsNum);
            othedk.push(item.openNum);
          }
        );
        console.log("initChart" + otherrq);
        console.log("initChart" + otherqqs);
        console.log("initChart" + othewx);
        console.log("initChart" + othedk);

        option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            }
          },
          grid: {
            right: '5%',
            left: '3%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: otherrq,
          },
          yAxis: {
            type: 'value'
          },
          legend: {
            data: ['请求', '无效', '打开'],
            top: '0%'
          },
          series: [
            {
              data: otherqqs,
              type: 'bar',
              name: '请求',
              itemStyle: {
                color: '#41B883'
              }
            },
            {
              data: othewx,
              type: 'bar',
              name: '无效',
              itemStyle: {
                color: '#ff0000'
              }
            },
            {
              data: othedk,
              type: 'bar',
              name: '打开',
              itemStyle: {
                color: '#FF9800'
              }
            }
          ]
        };
        option && this.chartContainer.setOption(option);
      });
    },


    getList() {
      this.loading = true;
       getStatdaylist(this.queryParams).then(response => {

         this.tableData = response.data.info.dataList;
         console.log("getList"+this.tableData);
         this.loading = false;
         // 数据加载完成后再初始化图表
         this.$nextTick(() => {
           this.initChart();
         });
       });
      getStatdayTotalList(this.queryParams).then(response => {
        var requestNum='0';
        var deliveredNum='0';
        var deliveredPercent='0';
        var invalidEmailsNum='0';
        var invalidEmailsPercent='0';
        var openNum='0';
        var openPercent='0';
        var spamReportedNum='0';
        var spamReportedPercent='0';
        var unsubscribeNum='0';
        var unsubscribePercent='0';
        if (response.data.info.dataList != null)
        {
          requestNum = response.data.info.dataList.requestNum;
          deliveredNum = response.data.info.dataList.deliveredNum;
          deliveredPercent = response.data.info.dataList.deliveredPercent;
          invalidEmailsNum = response.data.info.dataList.invalidEmailsNum;
          invalidEmailsPercent = response.data.info.dataList.invalidEmailsPercent;
          openNum = response.data.info.dataList.openNum;
          openPercent = response.data.info.dataList.openPercent;
          spamReportedNum = response.data.info.dataList.spamReportedNum;
          spamReportedPercent = response.data.info.dataList.spamReportedPercent
          unsubscribeNum = response.data.info.dataList.unsubscribeNum;
          unsubscribePercent = response.data.info.dataList.unsubscribePercent;
        }

          this.metrics = [];
          let obj0 = {};
          obj0['id'] = "requests";
          obj0['title'] = "请求";
          obj0['value'] = requestNum;
          obj0['percentage'] = "100";
          this.metrics.push(obj0);
          let obj1 = {};
          obj1['id'] = "delivered";
          obj1['title'] = "送达";
          obj1['value'] = deliveredNum;
          obj1['percentage'] = deliveredPercent;
          this.metrics.push(obj1);

          let obj2 = {};
          obj2['id'] = "processed";
          obj2['title'] = "计费邮件";
          obj2['value'] = deliveredNum;
          obj2['percentage'] = deliveredPercent;
          this.metrics.push(obj2);
          let obj3 = {};
          obj3['id'] = "invalid";
          obj3['title'] = "无效邮件";
          obj3['value'] = invalidEmailsNum;
          obj3['percentage'] = invalidEmailsPercent;
          this.metrics.push(obj3);
          let obj4 = {};
          obj4['id'] = "opened";
          obj4['title'] = "打开";
          obj4['value'] = openNum;
          obj4['percentage'] =openPercent;
          this.metrics.push(obj4);
          let obj5 = {};
          obj5['id'] = "complaint";
          obj5['title'] = "垃圾举报";
          obj5['value'] = spamReportedNum;
          obj5['percentage'] =spamReportedPercent;
          this.metrics.push(obj5);
          let obj6 = {};
          obj6['id'] = "unsubscribe";
          obj6['title'] = "取消订阅";
          obj6['value'] = unsubscribeNum;
          obj6['percentage'] = unsubscribePercent;
          this.metrics.push(obj6);

      });
    },
    getInvalidStatList()
    {
      this.loading = true;
      getInvalidstatlist(this.queryParams).then(response => {

        this.invalidstatData = response.data.info.dataList;
        this.loading = false;
      });
    },
    getSenderList() {
      this.loading = true;
      listEmailManage(this.queryParams).then(response => {
        this.senderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    beforeDestroy() {
      if (this.chartContainer) {
        this.chartContainer.dispose()
      }
      window.removeEventListener('resize', this.resizeChart);
    },
    resizeChart() {
      if (this.chartContainer) {
        this.chartContainer.resize();
      }
    },
    handleQuery() {
      this.getList();
      this.getInvalidStatList();
    },
    handlerq() {
      if (this.radio == 1) {
        this.valueTime = [];
        this.valueTime[0] = GetDayA(1);;
        this.valueTime[1] = GetMonB();
      }else if (this.radio == 2) {
        this.valueTime = [];
        this.valueTime[0] = GetMonA(1);
        this.valueTime[1] = GetMonB();
      }else if (this.radio == 3) {
        this.valueTime = [];
        this.valueTime[0] = GetMonA(3);
        this.valueTime[1] = GetMonB();
      }

      if (this.valueTime[0] == undefined || this.valueTime[1] == undefined) {
        this.$message.warning("请选择时间")
        return;
      }

      this.queryParams.startDate = new Date(this.valueTime[0]);
      this.queryParams.endDate = new Date(this.valueTime[1]);

      console.log(this.queryParams.startDate);
      console.log(this.queryParams.endDate);
      
      this.handleQuery();
    },
    handleSelectChange(value)
    {
      this.handleQuery();
    },
  },

}
</script>

<style scoped>
.dashboard {
  padding: 20px;
  background: #f5f7fa;
}

.nav-tabs {
  margin-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.tab {
  padding: 10px 20px;
  margin-right: 4px;
  border: none;
  background: none;
  cursor: pointer;
}

.tab.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.metrics-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.metric-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  border-left: 4px solid #ddd;
  transition: transform 0.2s ease;
}

.metric-card:hover {
  transform: translateY(-2px);
}

/* 数字卡片颜色样式 */
.metric-blue {
  border-left-color: #409EFF;
}

.metric-blue .metric-value {
  color: #409EFF;
}

.metric-green {
  border-left-color: #67C23A;
}

.metric-green .metric-value {
  color: #67C23A;
}

.metric-purple {
  border-left-color: #9C27B0;
}

.metric-purple .metric-value {
  color: #9C27B0;
}

.metric-red {
  border-left-color: #F56C6C;
}

.metric-red .metric-value {
  color: #F56C6C;
}

.metric-orange {
  border-left-color: #E6A23C;
}

.metric-orange .metric-value {
  color: #E6A23C;
}

.metric-yellow {
  border-left-color: #F39C12;
}

.metric-yellow .metric-value {
  color: #F39C12;
}

.metric-gray {
  border-left-color: #909399;
}

.metric-gray .metric-value {
  color: #909399;
}

.metric-title {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
  font-weight: 500;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
  line-height: 1.2;
}

.metric-percentage {
  color: #909399;
  font-size: 13px;
  background: #f5f7fa;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-block;
}

.chart-section {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 10px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-controls {
  display: flex;
  gap: 10px;
}

.control-btn {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.control-btn.active {
  color: #409EFF;
  border-color: #409EFF;
}

.chart {
  height: 400px;
}
.stats-dashboard {
  padding: 20px;
  background: #f5f7fa;
}

.tab-navigation {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.tab-button {
  padding: 8px 16px;
  border: none;
  background: none;
  cursor: pointer;
  color: #606266;
  position: relative;
}

.tab-button.active {
  color: #0052D9;
}

.tab-button.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background: #0052D9;
}

.export-section {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.export-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: #0052D9;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow-x: auto;
  margin-bottom: 20px;
}

.stats-table {
  width: 100%;
  border-collapse: collapse;
}

.stats-table th,
.stats-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

.stats-table th {
  background: #f5f7fa;
  color: #909399;
  font-weight: normal;
}

.stats-table td {
  color: #606266;
}

.percentage {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.footer-notes {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.footer-notes p {
  margin: 4px 0;
}
</style>
